<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :cols="2" formType="add" :labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <div v-if="isBalanceShow">
      <BasePrint ref="print" :data="printList" template="repair/repairReception/feesSettlement/finalStatementTemplateForPB" />
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button type="primary" icon="el-icon-printer" :loading="printBtnLoading" @click="getBalancePrintData">打 印</el-button>
      <el-button @click="closeDialog">取 消</el-button>
    </div>

    <!-- 打印结算单 -->
    <BasePrint ref="print" :data="printList" template="repair/repairReception/feesSettlement/finalStatementTemplate" />
    <!-- 结算单江苏 -->
    <BasePrint ref="printJS" :data="printList" template="repair/repairReception/feesSettlement/finalStatementTemplateJS" />
    <!-- 结算单上海 -->
    <BasePrint ref="printSH" :data="printList" template="repair/repairReception/feesSettlement/finalStatementTemplateSH" />
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import * as types from '@/api/common/auth/roleManage/types';
import { queryTechnician } from '@/api/repair/repairAssign/repairAssign';
import { getAllUser } from '@/api/finance/advancesReceived/register';
import { getSfqfSelect } from '@/api/repair/repairReception/customer';
import moment from 'moment';
import QRcode from 'qrcode';
import {
  findUrlQR,
  queryPrintData,
  getAdviceLabour,
  getAdvicePart,
  getRepairTypes,
  getLabourWorkData,
  getPartWorkData,
  queryRoLabourByRoNO,
  queryRoRepairPartByRoNO,
  queryRoAddItemByRoNO,
  queryCompanyInforById,
  pdfBalance,
  queryPrintLabourDataList,
  queryPrintRepartPartDataList,
  queryPartSaleOrderPrintData,
  queryOrderSuggestLabour
} from '@/api/repair/repairReception/feesSettlement';
import { searchRoleByCode } from '@/api/common/empSelect/index';
import { findAllRepair } from '@/api/repair/basicParameters';
import { getSeries, getModel } from '@/api/customerRepair/customerCare/insuranceDueRemind/index';
import dictCode from '@/utils/dictCode';
import { getCompanyId } from '@/assets/js/auth';
import { queryVipInfoByRono, queryVipInfoByBillNo } from '@/api/finance/repairFinance/cancelFinance';

export default {
  name: 'printBalance',
  mixins: [dictionary],
  props: ['printBalanceData'],
  data() {
    this.saveData = null;
    return {
      formList: this.createFormList(),
      serviceAdvisorData: [], // 服务工程师列表
      printList: {}, // 结算单数据
      vehicledList: {}, // 竣工合格证
      isBalanceShow: false,
      repairList: [], // 维修列表类型
      allUser: [],
      sfqf: [],
      roStatus: [],
      printBtnLoading: false,
      userList: {}, // 全部用户数据(翻译用)
      wechatCodeHost: 'https://miniprogram.faw-vw.com/appraise/code'
    };
  },
  computed: {
    ...mapState('app', ['btnLoading']),
    addBtnState() {
      return this.btnLoading[types.YAN_ROLE_ADD];
    }
  },
  mounted() {
    console.log('printBalanceData', this.printBalanceData);
    this.getAllUser();
    this.getSfqfSelect();
    // this.getBalancePrintData();
    this.serviceConsultant(); // 服务工程师
    this.getRepairTypesFun(); // 维修类型
  },
  methods: {
    createFormList() {
      return [
        // {
        //   type: 'SELECT',
        //   label: '收费对象',
        //   fieldName: 'id',
        //   placeholder: '请选择',
        //   itemList: []
        //   // rules: [{ required: true, message: '请选择收费对象', trigger: 'blur' }]
        // },
        {
          type: 'SELECT',
          label: '是否打印税额',
          fieldName: 'showTax',
          placeholder: '请选择',
          initialValue: 10041002,
          itemList: this.createDictList('1004')
        },
        // {
        //   type: 'SELECT',
        //   label: '是否打印维修建议',
        //   fieldName: 'suggesstion',
        //   placeholder: '请选择',
        //   initialValue: 10041001,
        //   change: val => {
        //     this.printList['ISSuggesstion'] = val;
        //   },
        //   itemList: this.createDictList('1004'),
        //   rules: [{ required: false, message: '请选择是否打印维修建议', trigger: 'change' }]
        // },
        {
          type: 'SELECT',
          label: '是否打印会员信息',
          fieldName: 'printVIP',
          initialValue: 10041001,
          itemList: this.createDictList('1004')
        }
      ];
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    async getAllUser() {
      const res = await getAllUser();
      this.allUser = res.data;
      let obj = {};
      res.data.map(item => {
        obj[item.userId] = item.employeeName;
      });
      this.userList = obj;
      this.queryTechnician();
    },
    async getSfqfSelect() {
      const res = await getSfqfSelect();
      this.sfqf = res.data;
    },
    async queryTechnician() {
      const res = await queryTechnician(this.roNo);
      let technician = res.data;
      for (const item of technician) {
        item.TECHNICIAN_NAME = this.allUser.find(x => x.userId == item.TECHNICIAN).employeeName;
      }
      technician.unshift({ TECHNICIAN: '-1', TECHNICIAN_NAME: '全部' });
      this.formList.find(x => x.fieldName === 'id').itemList = technician.map(x => ({ value: x.TECHNICIAN, text: x.TECHNICIAN_NAME }));
    },
    openPrint() {
      this.$refs.formPanel.SUBMIT_FORM();
      if (this.saveData != null) {
        this.isBalanceShow = true;
        this.$nextTick(() => {
          this.$refs.print.EXCUTE_PRINT();
        });
      } else {
        this.$notify.error({ title: '提示信息', message: '有必填项未填写!' });
      }
    },
    closeDialog() {
      this.$emit('close', false);
    },

    // 根据userId查employeeName
    getEmployeeName(userId) {
      const item = this.serviceAdvisorData.find(x => {
        return x.value == userId;
      });
      console.log(item, 'f服务工程师');
      return item ? item.text : '';
    },
    // 服务工程师接口数据
    async serviceConsultant() {
      let testDrive = { role: dictCode.SERVICE_CONSULTANT };
      const res = await searchRoleByCode(testDrive);
      this.serviceAdvisorData = res.data.map(x => ({ text: x.employeeName, value: x.userId }));
      console.log(JSON.stringify(this.serviceAdvisorData), '服务工程师');
    },
    // 根据code查维修类型名称
    getRepairTypeName(code) {
      const item = this.repairList.find(x => {
        return x.value == code;
      });
      return item ? item.text : '';
    },
    // 获取维修类型
    async getRepairTypesFun() {
      const res = await getRepairTypes(this.dmsFunc);
      this.repairList = res.data.map(x => ({ value: x.REPAIR_TYPE_CODE, text: x.REPAIR_TYPE_NAME }));
    },

    // 工单结算单打印
    async getBalancePrintData() {
      let totalData = '', // 整体数据
        companyData = '', // 根据公司id获取公司信息
        repairProjectData = '', // 维修项目数据
        repairMaterialData = '', // 维修材料数据
        additionData = '', // 附加项目数据
        adviceData = '', // 获取维修建议数据
        showTax = false, // 是否打印税金
        printVIP = false, // 是否打印会员
        qrCodeData = '', // 付款二维码
        serverManagerName = '', // 服务总监
        remarkParams = [], // 说明
        wechatQrCode = '', // 小程序二维码
        settlementMode = '',
        vipCardData = {};
      // // 如果打印税额的数组长度不为0 判定需要打印税额
      if (this.formList.find(item => item.fieldName === 'showTax').initialValue == 10041001) {
        showTax = true;
      }
      // // 如果打印会员的数组长度不为0 判定需要打印会员
      if (this.formList.find(item => item.fieldName === 'printVIP').initialValue == 10041001) {
        printVIP = true;
      }

      this.printBtnLoading = true;

      // 获取当前经销商数据与客户数据
      try {
        let balanceNumber = this.printBalanceData.BALANCE_NO == undefined ? 1 : this.printBalanceData.BALANCE_NO;
        totalData = await queryPrintData(this.printBalanceData.RO_NO, balanceNumber);
      } catch (err) {
        console.log(err, '获取打印经销商与客户数据失败');
      }

      // 获取公司信息
      try {
        companyData = await queryCompanyInforById({
          owenrCode: getCompanyId()
        });
      } catch (err) {
        console.log(err, '获取公司信息失败');
      }

      // 获取服务总监
      try {
        let params = { role: dictCode.SERVE_MAJORDOM };
        serverManagerName = (await searchRoleByCode(params)).data[0].employeeName;
      } catch (err) {
        console.log('获取服务总监失败', err);
      }

      // 维修项目  queryRoLabourByRoNO,  row.RO_NO
      try {
        repairProjectData = await queryPrintLabourDataList(this.printBalanceData.RO_NO);
      } catch (err) {
        console.log(err, '获取维修项目打印数据失败');
      }

      // 维修材料 queryRoRepairPartByRoNO, row.RO_NO
      if (this.printBalanceData.BALANCE_NO) {
        try {
          // repairMaterialData = await queryRoRepairPartByRoNO(this.printBalanceData.RO_NO);
          repairMaterialData = await queryPrintRepartPartDataList(this.printBalanceData.BALANCE_NO);
        } catch (err) {
          console.log(err, '获取维修材料打印数据失败');
        }
      }

      // 附加项目 queryRoAddItemByRoNO,  row.RO_NO\
      try {
        additionData = await queryRoAddItemByRoNO(this.printBalanceData.RO_NO);
      } catch (err) {
        console.log(err, '获取附加项目打印数据失败');
      }

      // 获取维修建议
      try {
        // adviceData = await getAdviceLabour(this.printBalanceData.VIN, this.printBalanceData.RO_NO);
        adviceData = await queryOrderSuggestLabour(this.printBalanceData.RO_NO || '');
      } catch (err) {
        console.log(err, '获取维修建议失败');
      }

      // 获取收费二维码
      let ownerNo = '';
      // if (this.printData.type === 'roNo') {
      ownerNo = this.printBalanceData.OWNER_NO;

      // } else {
      //   ownerNo = this.printData.CUSTOMER_CODE;
      // }
      // 如果是维修业务打印直接获取工单信息里面的车主编号
      // if (this.printData.isBusinessPrint === '10041001') {
      //  ownerNo = res.data.roInfo.OWNER_NO;
      // }
      try {
        qrCodeData = await this.getPayQrcode(this.printBalanceData.BALANCE_NO, ownerNo);
      } catch (err) {
        console.log(err, '获取二维码失败');
      }

      // 获取结算单说明 8107 - 8112
      try {
        let remarkArr = ['8107', '8108', '8109', '8110', '8111', '8112'];
        let remarkRes = (await findAllRepair()).data;
        let arr = [];
        for (let item in remarkRes) {
          if (remarkArr.includes(item)) {
            arr.push(remarkRes[item]);
          }
        }
        remarkParams = arr;
        settlementMode = remarkRes['9402'];
      } catch (err) {
        console.log(err, '获取结算说明失败');
      }

      // 如需打印会员信息获取会员信息
      if (printVIP) {
        let type = 1; // 预留--暂时只有工单 2 3分别为 销售单2，装饰单3 销售单号：salesPartNo，结算单号：balanceNo 装饰单号：billNo hxj 2020/2/24
        let fetchapi = type == 1 ? queryVipInfoByRono : queryVipInfoByBillNo;
        let params =
          type == 1
            ? {
                roNo: this.printBalanceData.RO_NO
              }
            : {
                orderType: row.SALES_PART_NO ? 2 : 3,
                salesPartNo: row.SALES_PART_NO || '',
                billNo: row.BILL_NO || '',
                balanceNo: row.BALANCE_NO
              };

        try {
          let res = await fetchapi(params);
          if (res.resultCode == 200 && res.data.result == true) {
            vipCardData = res.data.ReturnMemberInfo;
          }
        } catch (err) {
          console.log('获取会员信息失败');
        }
      }
      this.printBtnLoading = false;

      let payTypeCode = ''; // 付款方式
      let arrBalance = false; // 是否欠收结算
      try {
        // 结算日期单独处理
        totalData && (totalData.data.roInfo.COMPLETE_TIME = totalData.data.roInfo.COMPLETE_TIME ? totalData.data.roInfo.COMPLETE_TIME.split('T')[0] : '');
        totalData && (totalData.data.roInfo.BALANCE_TIME = totalData.data.roInfo.BALANCE_TIME ? totalData.data.roInfo.BALANCE_TIME.split(' ')[0] : '');
        // 翻译部分数据
        totalData && (totalData.data.roInfo.TRACE_TIME = this.createDictText(totalData.data.roInfo.TRACE_TIME, '8029'));
        totalData.data.roInfo.SERVICE_ADVISOR = this.userList[totalData.data.roInfo.SERVICE_ADVISOR] || '';
        totalData.data.roInfo.INSPECTOR = this.userList[totalData.data.roInfo.INSPECTOR] || totalData.data.roInfo.INSPECTOR;
        repairProjectData.data.map(item => (item.LABOUR_PROPERTY = this.createDictText(item.LABOUR_PROPERTY, '8104')));
        payTypeCode = totalData.data.roInfo.PAY_TYPE_CODE;
        arrBalance = totalData.data.roInfo.ARR_BALANCE == '10041001';
        // 结算人
        let createBy = totalData.data.roInfo.CREATED_BY;
        totalData.data.roInfo.CREATED_BY_NAME = this.userList[createBy];
      } catch (err) {
        console.log('翻译数据失败', err);
      }

      // 生成小程序二维码
      try {
        let repairCode = totalData.data.roInfo.REPAIR_TYPE_CODE;
        let dataUrl =
          repairCode == 0 || repairCode == 2
            ? `${this.wechatCodeHost}?dealerCode=${companyData.data.ascCode}&vin=${totalData.data.roInfo.VIN}&roType=${repairCode}&roNo=${totalData.data.roInfo.RO_NO}&startDate=${totalData.data.roInfo.RO_CREATE_DATE}&serviceConsultant=${totalData.data.roInfo.SERVICE_ADVISOR}`
            : '';
        wechatQrCode = await QRcode.toDataURL(dataUrl, {
          margin: 0
        });
      } catch (err) {
        console.log(err, '生成卓越二维码失败');
      }

      this.printList = {
        ...totalData.data,
        repairProjectData: repairProjectData.data,
        repairMaterialData: repairMaterialData.data,
        additionData: additionData.data,
        adviceData: adviceData.data,
        payQrCode: qrCodeData,
        showTax: showTax,
        printVIP: printVIP,
        companyData: companyData.data || {},
        remarkParams,
        vipCardData,
        serverManagerName,
        payTypeCode,
        arrBalance,
        wechatQrCode,
        settlementMode
      };

      if (companyData.data && companyData.data.province == 320000) {
        // 江苏
        this.$refs.printJS.EXCUTE_PRINT();
      } else if (companyData.data && companyData.data.province == 310000) {
        // 上海
        this.$refs.printSH.EXCUTE_PRINT();
      } else {
        this.$refs.print.EXCUTE_PRINT();
      }
    },
    // 获取二维码改造
    async getPayQrcode(BALANCE_NO, OWNER_NO) {
      // 获取收费对象
      // let object = this.formList.find(item => item.fieldName === 'object').initialValue;
      // 判断收费对象是否与结算单收费对象一致一致则查询二维码
      // console.log(object, OWNER_NO, BALANCE_NO, BALANCE_NO);
      if (BALANCE_NO !== '' && BALANCE_NO !== undefined) {
        const res = await findUrlQR(OWNER_NO, BALANCE_NO);
        console.log(res, 'res');

        if (res.resultCode === 200) {
          let url = res.data.GOTO_URL;
          this.GOTO_URL = url;
          if (url !== undefined && url !== '') {
            const setUrl = await QRcode.toDataURL(url);
            return setUrl;
          }
        } else {
          throw new Error(res);
        }
      } else {
        throw new Error('收费对象与结算单收费对象不符');
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
